package cn.online.zhuanshenben.web;

import cn.online.zhuanshenben.entity.Advtise;
import cn.online.zhuanshenben.entity.Sadmin;
import cn.online.zhuanshenben.service.AdminService;
import cn.online.zhuanshenben.service.AdvtiseService;
import cn.online.zhuanshenben.util.RedisTool;
import cn.online.zhuanshenben.util.SerializeUtil;
import cn.online.zhuanshenben.util.StrUtil;
import cn.online.zhuanshenben.vo.Page;
import cn.online.zhuanshenben.vo.Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@WebServlet("*.cmd")
public class AdminServlet extends BaseServlet {

    protected Result login(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        String u = req.getParameter("uname");
        String p = req.getParameter("upass");
        String vcode = req.getParameter("vcode");
        boolean v = false;
        //
        String key = req.getHeader("tokenkey");

        RedisTool redis = new RedisTool();
        String codeAndTime = redis.get_str(key);
        redis.getJedis().close();
        if (codeAndTime != null) {
            if (vcode.equalsIgnoreCase(codeAndTime)) {
                v = true;
            }
        }
        if (!v) {
            return Result.error("验证码错误或者超时");
        }
        Sadmin admin = AdminService.ME.login(u, p);
        if (admin != null) {
            String id = UUID.randomUUID().toString();
            RedisTool t = new RedisTool();

            t.set_obj(id, SerializeUtil.serialize(admin), 1800);
            Result r = Result.success(admin, id);
            t.getJedis().close();
            return r;
        }
        //admin存session,key是随机字符串，key 发给客户端
        return Result.error("错误的用户名或者密码");
    }

    public Result genCode(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
        //>>>resp.reset();
        //resp.setContentType("image/jpeg");
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        Color c = new Color(200, 155, 255);
        g.setColor(c);
        g.fillRect(0, 0, 80, 40);
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        String key = UUID.randomUUID().toString();
        RedisTool t = new RedisTool();
        t.set_str(key, sb.toString(), 60);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        //req.getSession().setAttribute("piccode", sb.toString()+" "+System.currentTimeMillis());
        //ImageIO.write(bi, "JPG", resp.getOutputStream());
        ImageIO.write(bi, "JPG", bout);
        t.getJedis().close();
        return Result.success(StrUtil.toBase64(bout.toByteArray()), key);
    }

    //
    public Page<Advtise> advtises(HttpServletResponse resp, HttpServletRequest req) throws ServletException,
            IOException {
        String title = req.getParameter("title");
        String url = req.getParameter("url");
        int page = StrUtil.toInt(req.getParameter("page"), 1);
        int size = StrUtil.toInt(req.getParameter("size"), 10);
        Date start = StrUtil.toDate(req.getParameter("starttime"));
        Date end = StrUtil.toDate(req.getParameter("end"));
        return AdvtiseService.ME.search(title, url, start, end, page, size);
    }

    //上传,只上传一个图片，返回图片的地址
    public Result upload(HttpServletResponse resp, HttpServletRequest req) throws Exception {

        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(df);
        upload.setHeaderEncoding("utf-8");//设置字符集
        List<FileItem> fileItems = upload.parseRequest(req);//解析request

        for (FileItem f : fileItems) {
            if (f.getSize() < 1)//文件没有选择
                return Result.error("文件没有选择");
            if (f.getSize() > 1024 * 1024 * 4)
                return Result.error("文件太大！");

            String path = req.getServletContext().getRealPath("images");

            File file = new File(path);
            if (file.exists() == false)
                file.mkdirs();
            //防止重名
            String houzhui = f.getName().substring(f.getName().lastIndexOf('.'));
            if (!(houzhui.equals(".jpg") || houzhui.equals(".png")))
                return Result.error("格式" + houzhui + "不支持");
            String newName = UUID.randomUUID() + houzhui;
            f.write(new File(file, newName));

            return Result.success("images/" + newName,"上传成功");
        }
        return Result.error("图片没有选");
    }
}